﻿using MyUtil;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;

namespace KnightWeapons
{
    public abstract class BaseWeapons<T>: NetworkBehaviour where T : BaseWeaponData
    {                
        [Header("Common")]
        [SerializeField] protected LayerMask targetLayer = 1 << 7;
        [SerializeField] protected T weaponData;

        [Header("Timer")]        
        protected bool canAttack = true;
        protected Timer attackCdTimer;
        
        protected NetworkAnimator networkAnimator;
        protected Animator animator;

        protected bool isAttack = false;
        protected bool isResume = false;

        [SerializeField] protected Transform currentAimTransform;

        protected Knight knight;

        protected virtual void Init()
        {
            networkAnimator = GetComponent<NetworkAnimator>();
            animator = GetComponent<Animator>();
        }

        protected virtual void FindEnemy(float range)
        {                        
            if(isAttack)
                return;
            
            Collider2D[] collider2Ds=Physics2D.OverlapCircleAll(transform.position,range,targetLayer);            
            if(collider2Ds.Length<=0)
            {
                currentAimTransform = null;
                return;
            }

            float minDistance=range;
            Collider2D target=null;

            foreach(var collider in collider2Ds)
            {               
                float distance = Vector2.SqrMagnitude(transform.position-collider.transform.position);
                if(minDistance*minDistance>distance)
                {   
                    minDistance=distance;
                    target=collider;
                }
            }
            if(target != null)
                currentAimTransform=target.gameObject.transform;
            else
                currentAimTransform=null;
        }        
        
        protected virtual void OnAim()
        {
            var dis = currentAimTransform.position - transform.position;
            var direction = dis.normalized;
            var zAngle = Mathf.MoveTowardsAngle(
                transform.rotation.eulerAngles.z,
                Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg,
                360
            );
            var newRotation = Quaternion.Euler(0,0,zAngle);
            transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, weaponData.RotationSpeed);            
            if (dis.sqrMagnitude <= Mathf.Pow(weaponData.AttackDistance,2) && canAttack)
            {
                OnAttack();
            }
        }
        protected abstract void OnResume();
        protected abstract void OnAttack();
    }
}